package com.example.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.dto.DishDto;
import com.example.reggie.entity.Category;
import com.example.reggie.mapper.DishMapper;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.DishFlavor;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.DishFlavorService;
import com.example.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        Set<String> keys = stringRedisTemplate.keys("dish:*");
        if (keys!=null){
            stringRedisTemplate.delete(keys);
            System.err.println("redis delete.....");
        }
        this.save(dishDto);
        Long dishId = dishDto.getId();//菜品id

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(item ->{
            item.setDishId(dishId);
        });
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        Set<String> keys = stringRedisTemplate.keys("dish:*");
        if (keys!=null){
            stringRedisTemplate.delete(keys);
            System.err.println("redis delete.....");
        }
        this.updateById(dishDto);

        //先清除对应的口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        //再重新添加口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(item ->{
            item.setDishId(dishDto.getId());
        });
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public void updateStatus(List<Long> ids, int code) {
        Set<String> keys = stringRedisTemplate.keys("dish:*");
        if (keys!=null){
            stringRedisTemplate.delete(keys);
            System.err.println("redis delete.....");
        }

        List<Dish> list = new ArrayList<>();
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(code);
            list.add(dish);
        }
        this.updateBatchById(list);
    }

    @Override
    public IPage<DishDto> toDtoPage(int page, int pageSize, String name) {
        IPage<Dish> dishPage = new Page<>(page, pageSize);
        IPage<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        page(dishPage, lqw);
        //将关于dish的分页数据拷贝至dishDto的分页，除了records属性 后续需要自己处理
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //将查询到的数据取出
        List<Dish> records = dishPage.getRecords();
        //遍历通过菜品id查询菜品名称 并赋予dishDto
        List<DishDto> list = records.stream().map((item) -> {
            //new dishDto用于复制原先dish的数据，并通过id查询categoryName
            DishDto dishDto = new DishDto();
            //拷贝数据
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //通过id查询到category并取出categoryName
            Category category = categoryService.getById(categoryId);
            if (category != null) {

                String categoryName = category.getName();
                //set菜品名称
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());//转换为list<DishDto>
        dishDtoPage.setRecords(list);
        return dishDtoPage;
    }

    @Override
    @Cacheable(value = "dish",key = "#dish.categoryId + '_'+ #dish.status")
    public List<DishDto> toDtoList(Dish dish) {
//        String key = "dish:" + dish.getCategoryId() + "_" + dish.getStatus();
//        String json = stringRedisTemplate.opsForValue().get(key);
//        if (json != null && json != ""){
//            List list = JSON.parseObject(json, List.class);
//            return list;
//        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        String toJSONString = JSON.toJSONString(dishDtoList);
        //stringRedisTemplate.opsForValue().set(key,toJSONString,30, TimeUnit.MINUTES);
        return dishDtoList;
    }
}
